---
import { getDefaultConfig, getPlaylist, getAutoplay, getPosition, getMobileConfig, getTheme } from './MusicPlayerConfig.astro';
import WidgetLayout from "./WidgetLayout.astro";
import {i18n} from "../../i18n/translation";
import I18nKey from "../../i18n/i18nKey";
import {getTagUrl} from "../../utils/url-utils";
import ButtonTag from "../control/ButtonTag.astro";
import {getTagList} from "../../utils/content-utils";

const config = getDefaultConfig();
const playlist = getPlaylist(config);
const autoplay = getAutoplay(config);
const position = getPosition(config);
const mobileConfig = getMobileConfig(config);
const theme = getTheme(config);

// 根据主题色生成样式
const primaryColor = theme.primaryColor;
const backgroundColor = theme.backgroundColor;
const textColor = theme.textColor;
const className = Astro.props.class;
const style = Astro.props.style;
const tags = await getTagList();
const COLLAPSED_HEIGHT = "25rem";
const isCollapsed = false;
const isFullWidth = true;
const positionClasses = position === 'left' ? 'left-4' : 'right-4';

---
<WidgetLayout name={i18n(I18nKey.music)} id="music" isFullWidth={isFullWidth} isCollapsed={isCollapsed} collapsedHeight={COLLAPSED_HEIGHT} class={className} style={style}>
  <div id="music-player" class={``}>
    <!-- 移动端悬浮图标 -->
    <button
        id="music-toggle-btn"
        class="md:hidden fixed left-2 top-1/2 -translate-y-1/2 bg-blue-500 text-white rounded-full p-3 shadow-lg transition-all duration-300 hover:scale-110 focus:outline-none focus:ring-2 focus:ring-blue-400 z-50"
        title="打开音乐播放器"
    >
      <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
        <path d="M18 3a1 1 0 00-1.196-.98l-10 2A1 1 0 006 5v9.114A4.369 4.369 0 005 14c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2V7.82l8-1.6v5.894A4.37 4.37 0 0015 12c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2V3z"/>
      </svg>
    </button>
    <div id="player-container" class="music-player-container bg-white dark:bg-slate-800 shadow-2xl dark:border-slate-700 overflow-hidden min-w-[280px] md:block transform transition-all duration-300 hidden">
      <!-- 关闭按钮 - 移动端显示 -->
      <button
          id="close-player-btn"
          class="md:hidden absolute top-2 right-2 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 transition-colors z-10"
          title="关闭播放器"
      >
        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"/>
        </svg>
      </button>
      <!-- 封面区域 -->
      <div class="relative">
        <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
        <!-- 播放状态指示器 -->
        <div id="playing-indicator" class="absolute top-2 right-2 bg-blue-500 text-white px-2 py-1 rounded-full text-xs font-medium opacity-0 transition-opacity duration-300">
          播放中
        </div>
      </div>

      <!-- 信息区域 -->
      <div class="p-4">
        <div class="text-center mb-4">
          <h3 id="song-title" class="text-lg font-bold text-slate-900 dark:text-slate-100 truncate">
            {playlist[0].title}
          </h3>
          <p id="song-artist" class="text-sm text-slate-600 dark:text-slate-400">
            {playlist[0].artist}
          </p>
        </div>

        <!-- 进度条 -->
        <div class="mb-4">
          <div class="flex justify-between text-xs text-slate-500 dark:text-slate-400 mb-1">
            <span id="current-time">0:00</span>
            <span id="total-time">0:00</span>
          </div>
          <div class="relative">
            <div class="h-1 bg-slate-200 dark:bg-slate-700 rounded-full">
              <div id="progress-bar" class="h-1 bg-blue-500 rounded-full transition-all duration-100" style="width: 0%"></div>
            </div>
            <input
                id="progress-slider"
                type="range"
                min="0"
                max="100"
                value="0"
                class="absolute inset-0 w-full h-1 opacity-0 cursor-pointer"
            />
          </div>
        </div>

        <!-- 控制按钮 -->
        <div class="flex justify-center items-center space-x-4 mb-4">
          <button
              id="prev-btn"
              class="p-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100 transition-colors"
              title="上一首"
          >
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path d="M8.445 14.832A1 1 0 0010 14v-8a1 1 0 00-1.555-.832L5 8.445V6a1 1 0 00-2 0v8a1 1 0 002 0v-2.445l3.445 3.277z"/>
            </svg>
          </button>

          <button
              id="play-btn"
              class="p-3 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors shadow-lg"
              title="播放/暂停"
          >
            <svg id="play-icon" class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
              <path d="M6.3 2.841A1.5 1.5 0 004 4.11V15.89a1.5 1.5 0 002.3 1.269l9.344-5.89a1.5 1.5 0 000-2.538L6.3 2.84z"/>
            </svg>
            <svg id="pause-icon" class="w-6 h-6 hidden" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"/>
            </svg>
          </button>

          <button
              id="next-btn"
              class="p-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100 transition-colors"
              title="下一首"
          >
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path d="M11.555 5.168A1 1 0 0010 6v8a1 1 0 001.555.832L15 11.555V14a1 1 0 002 0V6a1 1 0 00-2 0v2.445l-3.445-3.277z"/>
            </svg>
          </button>
        </div>

        <!-- 音量控制 -->
        <div class="flex items-center space-x-2">
          <button
              id="volume-btn"
              class="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100 transition-colors"
              title="静音/取消静音"
          >
            <svg id="volume-icon" class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.617.824L4.5 14H2a1 1 0 01-1-1V7a1 1 0 011-1h2.5l3.883-2.824zM14.5 10a4.5 4.5 0 01-1.61 3.443l.857.857A6.5 6.5 0 0016.5 10a6.5 6.5 0 00-2.753-5.443l-.857.857A4.5 4.5 0 0114.5 10z" clip-rule="evenodd"/>
            </svg>
          </button>
          <input
              id="volume-slider"
              type="range"
              min="0"
              max="100"
              value="50"
              class="flex-1 h-1 bg-slate-200 dark:bg-slate-700 rounded-full appearance-none cursor-pointer"
          />
        </div>

        <!-- 播放列表 -->
        <div class="mt-4 border-t border-slate-200 dark:border-slate-700 pt-2">
          <button
              id="playlist-toggle"
              class="w-full text-sm text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100 transition-colors flex items-center justify-center"
          >
            <span>播放列表</span>
            <svg class="w-4 h-4 ml-1" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"/>
            </svg>
          </button>
          <div id="playlist" class="hidden mt-2 max-h-32 overflow-y-auto">
            {playlist.map((song, index) => (
                <div
                    class="playlist-item p-2 text-sm hover:bg-slate-100 dark:hover:bg-slate-700 rounded cursor-pointer transition-colors"
                    data-index={index}
                >
                  <div class="font-medium text-slate-900 dark:text-slate-100">{song.title}</div>
                  <div class="text-xs text-slate-600 dark:text-slate-400">{song.artist}</div>
                </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  </div>
</WidgetLayout>


<style>
  :root {
    --music-primary-color: rgb(55, 125, 244);
    --music-bg-color: #ffffff;
    --music-text-color: #374151;
  }

  .music-player-container {
    backdrop-filter: blur(10px);
    background: var(--music-bg-color);
    color: var(--music-text-color);
  }
  
  /* 移动端优化样式 */
  @media (max-width: 767px) {
    .music-player-container {
      position: fixed !important;
      top: 50% !important;
      left: 50% !important;
      transform: translate(-50%, -50%) scale(0.8) !important;
      max-width: 90vw;
      max-height: 80vh;
      z-index: 1000 !important;
      opacity: 0;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
      border-radius: 12px !important;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2) !important;
    }
    
    .music-player-container.block {
      opacity: 1 !important;
      transform: translate(-50%, -50%) scale(1) !important;
    }
    
    #music-toggle-btn {
      position: fixed;
      left: 1rem;
      top: 50%;
      transform: translateY(-50%);
      z-index: 1001;
      transition: all 0.3s ease !important;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
    }
    
    #music-toggle-btn:hover {
      transform: translateY(-50%) scale(1.1) !important;
    }
    
    #music-toggle-btn.opacity-50 {
      opacity: 0.7 !important;
    }
    
    /* 移动端遮罩层 */
    .mobile-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
      backdrop-filter: blur(2px);
      transition: opacity 0.3s ease;
    }
    
    /* 脉冲动画增强 */
    @keyframes pulse {
      0%, 100% { 
        transform: scale(1);
        box-shadow: 0 4px 12px var(--music-primary-color);
      }
      50% { 
        transform: scale(1.1);
        box-shadow: 0 6px 20px var(--music-primary-color);
      }
    }
    
    /* 禁止背景滚动 */
    .mobile-no-scroll {
      overflow: hidden !important;
      height: 100vh !important;
      position: fixed !important;
      width: 100% !important;
    }
    
    /* 小屏幕适配 */
    @media (max-width: 480px) {
      .music-player-container {
        max-width: 85vw !important;
        max-height: 75vh !important;
      }
      
      #music-toggle-btn {
        left: 8px !important;
        width: 48px !important;
        height: 48px !important;
      }
    }
  }
  
  /* 桌面端样式 */
  @media (min-width: 768px) {
    #music-toggle-btn {
      display: none;
    }
  }
  
  #progress-slider::-webkit-slider-thumb {
    appearance: none;
    width: 12px;
    height: 12px;
    background: var(--music-primary-color);
    border-radius: 50%;
    cursor: pointer;
  }
  
  #volume-slider::-webkit-slider-thumb {
    appearance: none;
    width: 12px;
    height: 12px;
    background: var(--music-primary-color);
    border-radius: 50%;
    cursor: pointer;
  }
  
  .dark #volume-slider::-webkit-slider-thumb {
    background: var(--music-primary-color);
  }
  
  /* 移动端图标动画 */
  .music-icon-pulse {
    animation: pulse 2s infinite;
  }
  
  @keyframes pulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.1);
    }
    100% {
      transform: scale(1);
    }
  }
  
  /* 防止移动端滚动 */
  .mobile-no-scroll {
    overflow: hidden;
  }
</style>

<script define:vars={{ playlist, autoplay }}>
  class MusicPlayer {
    constructor(playlist, autoplay) {
      this.playlist = playlist;
      this.currentIndex = 0;
      this.isPlaying = false;
      this.audio = new Audio();
      this.audio.volume = 0.5;
      this.autoplay = autoplay;
      
      this.init();
    }

    init() {
      this.bindEvents();
      this.loadSong(this.currentIndex);
      
      if (this.autoplay) {
        this.play();
      }
    }

    bindEvents() {
      // 播放/暂停按钮
      document.getElementById('play-btn').addEventListener('click', () => {
        this.isPlaying ? this.pause() : this.play();
      });

      // 上一首/下一首
      document.getElementById('prev-btn').addEventListener('click', () => this.prev());
      document.getElementById('next-btn').addEventListener('click', () => this.next());

      // 进度条
      document.getElementById('progress-slider').addEventListener('input', (e) => {
        const percent = e.target.value / 100;
        this.audio.currentTime = percent * this.audio.duration;
      });

      // 音量控制
      document.getElementById('volume-slider').addEventListener('input', (e) => {
        this.audio.volume = e.target.value / 100;
        this.updateVolumeIcon();
      });

      // 音量按钮静音
      document.getElementById('volume-btn').addEventListener('click', () => {
        this.audio.muted = !this.audio.muted;
        this.updateVolumeIcon();
      });

      // 播放列表切换
      document.getElementById('playlist-toggle').addEventListener('click', () => {
        const playlist = document.getElementById('playlist');
        playlist.classList.toggle('hidden');
      });

      // 播放列表点击
      document.querySelectorAll('.playlist-item').forEach((item, index) => {
        item.addEventListener('click', () => {
          this.currentIndex = index;
          this.loadSong(this.currentIndex);
          this.play();
        });
      });

      // 音频事件
      this.audio.addEventListener('timeupdate', () => this.updateProgress());
      this.audio.addEventListener('ended', () => this.next());
      this.audio.addEventListener('loadedmetadata', () => this.updateDuration());
      this.audio.addEventListener('play', () => this.updatePlayButton(true));
      this.audio.addEventListener('pause', () => this.updatePlayButton(false));
    }

    loadSong(index) {
      const song = this.playlist[index];
      this.audio.src = song.url;
      
      document.getElementById('song-title').textContent = song.title;
      document.getElementById('song-artist').textContent = song.artist;

      // 更新播放列表高亮
      document.querySelectorAll('.playlist-item').forEach((item, i) => {
        item.classList.toggle('bg-blue-100', i === index);
        item.classList.toggle('dark:bg-blue-900', i === index);
      });
    }

    play() {
      this.isPlaying = true;
      this.audio.play();
      document.getElementById('playing-indicator').classList.remove('opacity-0');
    }

    pause() {
      this.isPlaying = false;
      this.audio.pause();
      document.getElementById('playing-indicator').classList.add('opacity-0');
    }

    prev() {
      this.currentIndex = (this.currentIndex - 1 + this.playlist.length) % this.playlist.length;
      this.loadSong(this.currentIndex);
      if (this.isPlaying) this.play();
    }

    next() {
      this.currentIndex = (this.currentIndex + 1) % this.playlist.length;
      this.loadSong(this.currentIndex);
      if (this.isPlaying) this.play();
    }

    updateProgress() {
      const percent = (this.audio.currentTime / this.audio.duration) * 100 || 0;
      document.getElementById('progress-bar').style.width = `${percent}%`;
      document.getElementById('progress-slider').value = percent;
      
      const currentTime = this.formatTime(this.audio.currentTime);
      document.getElementById('current-time').textContent = currentTime;
    }

    updateDuration() {
      const totalTime = this.formatTime(this.audio.duration);
      document.getElementById('total-time').textContent = totalTime;
    }

    updatePlayButton(playing) {
      const playIcon = document.getElementById('play-icon');
      const pauseIcon = document.getElementById('pause-icon');
      
      if (playing) {
        playIcon.classList.add('hidden');
        pauseIcon.classList.remove('hidden');
      } else {
        playIcon.classList.remove('hidden');
        pauseIcon.classList.add('hidden');
      }
    }

    updateVolumeIcon() {
      const volumeIcon = document.getElementById('volume-icon');
      const volumeBtn = document.getElementById('volume-btn');
      
      if (this.audio.muted || this.audio.volume === 0) {
        volumeIcon.innerHTML = `
          <path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v4.879l3.83-3.323a1 1 0 111.414 1.38l-4.83 4.83a1 1 0 01-1.414 0L4 10.879V14a1 1 0 01-1 1H2a1 1 0 01-1-1V7a1 1 0 011-1h2.5l3.883-2.824z" clip-rule="evenodd"/>
        `;
      } else {
        volumeIcon.innerHTML = `
          <path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.617.824L4.5 14H2a1 1 0 01-1-1V7a1 1 0 011-1h2.5l3.883-2.824zM14.5 10a4.5 4.5 0 01-1.61 3.443l.857.857A6.5 6.5 0 0016.5 10a6.5 6.5 0 00-2.753-5.443l-.857.857A4.5 4.5 0 0114.5 10z" clip-rule="evenodd"/>
        `;
      }
    }

    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins}:${secs.toString().padStart(2, '0')}`;
    }
  }

  // 移动端控制
  class MobileMusicController {
    constructor() {
      this.playerContainer = document.getElementById('player-container');
      this.toggleBtn = document.getElementById('music-toggle-btn');
      this.closeBtn = document.getElementById('close-player-btn');
      this.isOpen = false;
      this.overlay = null;
      
      this.init();
    }

    init() {
      // 创建遮罩层
      this.createOverlay();
      
      // 绑定移动端控制事件
      this.toggleBtn.addEventListener('click', () => this.togglePlayer());
      this.closeBtn.addEventListener('click', () => this.closePlayer());
      
      // 点击遮罩层关闭
      this.overlay.addEventListener('click', () => this.closePlayer());
      
      // 点击播放器外部关闭
      document.addEventListener('click', (e) => {
        if (this.isOpen && !this.playerContainer.contains(e.target) && !this.toggleBtn.contains(e.target)) {
          this.closePlayer();
        }
      });

      // ESC键关闭
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && this.isOpen) {
          this.closePlayer();
        }
      });

      // 监听窗口大小变化
      window.addEventListener('resize', () => this.handleResize());

      // 初始化状态
      this.handleResize();
      
      // 添加播放动画
      this.addPlayingAnimation();
    }

    createOverlay() {
      this.overlay = document.createElement('div');
      this.overlay.className = 'mobile-overlay hidden';
      document.body.appendChild(this.overlay);
    }

    togglePlayer() {
      this.isOpen = !this.isOpen;
      
      if (this.isOpen) {
        this.openPlayer();
      } else {
        this.closePlayer();
      }
    }

    openPlayer() {
      this.isOpen = true;
      
      // 显示播放器
      this.playerContainer.classList.remove('hidden');
      this.playerContainer.classList.add('block');
      
      // 显示遮罩层
      this.overlay.classList.remove('hidden');
      
      // 禁用背景滚动
      document.body.classList.add('mobile-no-scroll');
      
      // 图标状态
      this.toggleBtn.classList.add('opacity-50');
      
      // 添加展开动画
      this.animatePlayer('open');
    }

    closePlayer() {
      this.isOpen = false;
      
      // 隐藏播放器
      this.playerContainer.classList.add('hidden');
      this.playerContainer.classList.remove('block');
      
      // 隐藏遮罩层
      this.overlay.classList.add('hidden');
      
      // 恢复背景滚动
      document.body.classList.remove('mobile-no-scroll');
      
      // 图标状态
      this.toggleBtn.classList.remove('opacity-50');
      
      // 添加收起动画
      this.animatePlayer('close');
    }

    animatePlayer(action) {
      if (action === 'open') {
        this.playerContainer.style.transform = 'translate(-50%, -50%) scale(0.8)';
        this.playerContainer.style.opacity = '0';
        
        setTimeout(() => {
          this.playerContainer.style.transform = 'translate(-50%, -50%) scale(1)';
          this.playerContainer.style.opacity = '1';
        }, 10);
      }
    }

    addPlayingAnimation() {
      // 当音乐播放时，图标添加脉冲动画
      const audio = document.querySelector('#music-player audio');
      if (audio) {
        audio.addEventListener('play', () => {
          this.toggleBtn.classList.add('music-icon-pulse');
        });
        
        audio.addEventListener('pause', () => {
          this.toggleBtn.classList.remove('music-icon-pulse');
        });
      }
    }

    handleResize() {
      if (window.innerWidth >= 768) {
        // 桌面端
        this.playerContainer.classList.remove('hidden');
        this.toggleBtn.classList.add('hidden');
        this.overlay.classList.add('hidden');
        document.body.classList.remove('mobile-no-scroll');
        this.isOpen = true;
      } else {
        // 移动端
        this.playerContainer.classList.add('hidden');
        this.toggleBtn.classList.remove('hidden');
        this.overlay.classList.add('hidden');
        document.body.classList.remove('mobile-no-scroll');
        this.isOpen = false;
      }
    }
  }

  // 配置管理
  let config = null;
  
  async function loadConfig() {
    config = { playlist, autoplay };
    initPlayer();
  }

  function applyConfig() {
    if (!config || !config.enabled) {
      document.getElementById('music-player')?.remove();
      document.getElementById('music-toggle-btn')?.remove();
      return;
    }

    // 应用主题
    if (config.theme) {
      const root = document.documentElement;
      root.style.setProperty('--music-primary-color', config.theme.primaryColor);
      root.style.setProperty('--music-bg-color', config.theme.backgroundColor);
      root.style.setProperty('--music-text-color', config.theme.textColor);
    }

    initPlayer();
  }

  function initPlayer() {
    new MusicPlayer(config.playlist, config.autoplay);
    new MobileMusicController();
  }

  // 初始化播放器
  document.addEventListener('DOMContentLoaded', () => {
    loadConfig();
  });
</script>